package package1;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Vector;

public class TestForFileSplitter {

	@SuppressWarnings("unused")
	private static final int SIZE = 1024*1024;

	/**
	 * file splitter: split a file into many pieces
	 * essence: create a lot of file to load the content of the whole file
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		
		
//		splitFile();
//		mergeFile();
	}

	@SuppressWarnings("unused")
	private static void mergeFile() throws IOException {
		String fileName = "hello.docx";
		String dir = getDesktop()+"\\temp";
		Vector<FileInputStream> v = new Vector<FileInputStream>();
		v.add(new FileInputStream(dir+"\\1.part"));
		v.add(new FileInputStream(dir+"\\2.part"));
		
		SequenceInputStream sis = new SequenceInputStream(v.elements());
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(getDesktop(),fileName)));
		byte [] buf = new byte[1024];
		int len;
		while((len=sis.read(buf))!=-1){
			bos.write(buf,0,len);
			bos.flush();
		}
		bos.close();
		sis.close();
		
	}

	@SuppressWarnings("unused")
	private static void splitFile() throws IOException {
		String fileName = getDesktop()+"\\eclipse hot  keys.docx";
		int part = 2;
		File f = new File(fileName);
		int buffersize = (int) (f.length()/part);
		System.err.println("buffersize"+buffersize);
		FileInputStream fis = new FileInputStream(fileName);
		FileOutputStream fos = null;
		byte[]buf = new byte[buffersize];	int len; int fileCount = 1;
		File dir = new File(f.getParent()+"\\temp");
		if(!dir.exists()) dir.mkdirs();
		while((len = fis.read(buf))!=-1){
			fos = new FileOutputStream(dir.getPath()+"\\"+(fileCount++)+".part");
			fos.write(buf,0,len);
		}
		fis.close();fos.close();
		System.err.println("succeed");
		open(dir);
	}
	
	public static void openCurrentFolder() throws IOException {
		String aa = new File(new File("a").getAbsolutePath()).getParent();
		aa = System.getProperty("user.dir");
		open(aa);
	}
	
	private static void open(String fileName) throws IOException {
		open((new File(fileName)));
	}
	

	private static void open(File file) throws IOException {
		java.awt.Desktop.getDesktop().open(file);
	}

	public static String getDesktop(){
		return System.getenv("USERPROFILE")+"\\desktop";
		
	}
	
}
